package com.restkeeper.controller;

import com.restkeeper.dto.CreditDTO;
import com.restkeeper.dto.DetailDTO;
import com.restkeeper.dto.ReceiptDTO;
import com.restkeeper.entity.OrderDetailEntity;
import com.restkeeper.entity.OrderEntity;
import com.restkeeper.entity.OrderViewEntity;
import com.restkeeper.entity.ReverseOrder;
import com.restkeeper.service.IOrderDetailService;
import com.restkeeper.service.IOrderService;
import com.restkeeper.service.IReverseOrderService;
import com.restkeeper.store.entity.Dish;
import com.restkeeper.store.service.IDishService;
import com.restkeeper.tenant.TenantContext;
import com.restkeeper.utils.OrderPayType;
import com.restkeeper.utils.Result;
import com.restkeeper.utils.ResultCode;
import com.restkeeper.utils.SystemCode;
import com.restkeeper.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/order")
@Api(tags = {"下单,结账"})
public class OrderController {

    @Reference(version = "1.0.0",check = false)
    private IOrderService orderService;

    @Reference(version = "1.0.0",check = false)
    private IOrderDetailService orderDetailService;


    @Reference(version = "1.0.0",check = false)
    private IDishService dishService;

    @Reference(version = "1.0.0",check = false)
    private IReverseOrderService reverseOrderService;



    /**
     * 下单
     * @param orderVO
     * @return
     */
    @ApiOperation(value = "下单")
    @PostMapping("/add")
    public Result add(@RequestBody OrderVO orderVO){
        OrderEntity orderEntity=new OrderEntity();
        orderEntity.setTableId(orderVO.getTableId());
        orderEntity.setOperatorName(TenantContext.getLoginUserName());
        orderEntity.setOrderSource(SystemCode.ORDER_SOURCE_STORE);
        orderEntity.setTotalAmount(orderVO.getTotalAmount());
        orderEntity.setPersonNumbers(orderVO.getPersonNumbers());
        orderEntity.setPayStatus(SystemCode.ORDER_STATUS_NOPAY);
        if(!orderVO.getOrderRemark().isEmpty()){
            orderEntity.setOrderRemark(orderVO.getOrderRemark().toString());
        }
        orderEntity.setCreateTime(LocalDateTime.now());
        List<OrderDetailEntity> orderDetails =new ArrayList<>();
        orderVO.getDishs().forEach(dishVO -> {
            OrderDetailEntity orderDetailEntity =new OrderDetailEntity();
            orderDetailEntity.setTableId(orderVO.getTableId());
            orderDetailEntity.setDishPrice(dishVO.getPrice());
            orderDetailEntity.setDetailStatus(dishVO.getStatus());
            orderDetailEntity.setDishName(dishVO.getDishName());
            orderDetailEntity.setDishType(dishVO.getType());
            orderDetailEntity.setDishAmount(dishVO.getDishNumber()*dishVO.getPrice());
            orderDetailEntity.setDishId(dishVO.getDishId());
            orderDetailEntity.setDishNumber(dishVO.getDishNumber());
            orderDetailEntity.setFlavorRemark(dishVO.getFlavorList().toString());
            orderDetails.add(orderDetailEntity);
        });
        orderEntity.setOrderDetails(orderDetails);
        Result result=new Result();
        result.setStatus(ResultCode.success);
        String orderId = orderService.addOrder(orderEntity);
        result.setData(orderId);
        return result;
    }


    /**
     *加菜下单
     * @param orderId
     * @param details
     * @return
     */
    @ApiOperation(value = "加菜")
    @PostMapping("/plusDish/orderId/{orderId}")
    public Result orderPlusDish(@PathVariable String orderId, @RequestBody List<OrderDetailVO> details){
        OrderEntity orderEntity = orderService.getById(orderId);
        List<OrderDetailEntity> orderDetailEntities =new ArrayList<>();
        //当前加菜总金额
        int amount=0;
        for (OrderDetailVO detail : details) {
            OrderDetailEntity orderDetailEntity=new OrderDetailEntity();
            orderDetailEntity.setTableId(orderEntity.getTableId());
            orderDetailEntity.setDishPrice(detail.getPrice());
            orderDetailEntity.setDetailStatus(detail.getStatus());
            orderDetailEntity.setDishName(detail.getDishName());
            orderDetailEntity.setDishType(detail.getType());
            orderDetailEntity.setDishId(detail.getDishId());
            orderDetailEntity.setDishAmount(detail.getDishNumber()*detail.getPrice());
            Dish dish = dishService.getById(detail.getDishId());
            if(dish!=null){
                orderDetailEntity.setDishCategoryName(dish.getCategory().getName());
            }
            orderDetailEntity.setDishNumber(detail.getDishNumber());
            orderDetailEntity.setFlavorRemark(detail.getFlavorList().toString());
            orderDetailEntities.add(orderDetailEntity);
            amount+=orderDetailEntity.getDishAmount();
        }
        orderEntity.setTotalAmount(orderEntity.getTotalAmount()+amount);
        orderEntity.setOrderDetails(orderDetailEntities);
        Result result=new Result();
        result.setStatus(ResultCode.success);
        orderId = orderService.addOrder(orderEntity);
        result.setData(orderId);
        return result;
    }

    /**
     * 结账
     * @param payVO
     * @return
     */
    @ApiOperation(value = "结账")
    @PostMapping("/pay/orderId/{orderId}")
    public boolean pay(@PathVariable String orderId, @RequestBody PayVO payVO){
        OrderEntity orderEntity= orderService.getById(orderId);
        orderEntity.setPayAmount(payVO.getPayAmount());
        orderEntity.setPayStatus(SystemCode.ORDER_STATUS_PAYED);
        orderEntity.setPayType(payVO.getPayType());
        return orderService.pay(orderEntity);
    }

    @ApiOperation(value = "打印")
    @GetMapping("/print/{printType}/{orderId}")
    public boolean print(@PathVariable int printType,@PathVariable String orderId){
        orderService.print(printType,orderId,true);

        return true;
    }

    /**
     * 退菜
     * @param detailId
     * @param remarks
     * @return
     */
    @ApiOperation(value = "退菜")
    @PostMapping("/returnDish/{detailId}")
    public boolean returnDish(@PathVariable String detailId, @RequestBody List<String> remarks){
        DetailDTO detailDTO=new DetailDTO();
        detailDTO.setDetailId(detailId);
        detailDTO.setRemarks(remarks);
       return orderService.returnDish(detailDTO);
    }

    /**
     * 赠菜
     * @param detailId
     * @param remarks
     * @return
     */
    @ApiOperation(value = "赠菜")
    @PutMapping("/presentDish/{detailId}")
    public boolean presentDish(@PathVariable String detailId, @RequestBody  List<String> remarks){
        DetailDTO detailDTO=new DetailDTO();
        detailDTO.setDetailId(detailId);
        detailDTO.setRemarks(remarks);
        return orderService.presentDish(detailDTO);
    }

    /**
     * 反结账
     * @param orderId 反结账订单
     * @param remarks 反结账原因
     * @return
     */
    @ApiOperation(value = "反结账")
    @PutMapping("/reverse/{orderId}")
    public boolean reverse(@PathVariable String orderId, @RequestBody  List<String> remarks){
        ReverseOrder reverseOrder=new ReverseOrder();
        reverseOrder.setOrderId(orderId);
        reverseOrder.setRemark(remarks.toString());
        return reverseOrderService.reverse(reverseOrder);
    }


    @ApiOperation(value = "收据接口")
    @PostMapping("/receipt")
    public ReceiptPageVO<OrderViewEntity> receipt(@RequestBody ReceiptVO receiptVO){
        ReceiptDTO receiptDTO =new ReceiptDTO();
        BeanUtils.copyProperties(receiptVO,receiptDTO);
        //开始结束时间问题
        if (StringUtils.isNoneBlank(receiptVO.getStartDate())&&StringUtils.isNoneBlank(receiptVO.getEndDate())) {
            LocalDate startDate = LocalDate.parse(receiptVO.getStartDate(), DateTimeFormatter.ISO_LOCAL_DATE);
            LocalDateTime startDateTime = LocalDateTime.of(startDate, LocalTime.MIN);
            LocalDate endDate = LocalDate.parse(receiptVO.getEndDate(), DateTimeFormatter.ISO_LOCAL_DATE);
            LocalDateTime endDateTime = LocalDateTime.of(endDate, LocalTime.MAX);
            receiptDTO.setStartDate(startDateTime);
            receiptDTO.setEndDate(endDateTime);
        }
        Map<String,Integer> countMp=orderService.receiptCount(receiptDTO);
        ReceiptPageVO pageVO= new ReceiptPageVO<OrderViewEntity>(orderService.queryAllOrder(receiptDTO));
        pageVO.setAllPayAmount(countMp.get("totalAmount"));
        pageVO.setAlltotalAmount(countMp.get("payAmount"));
        return  pageVO;
    }

    @ApiOperation(value = "获取员工列表")
    @GetMapping("/getOperators")
    public List<String> getOperators(){
        return orderService.getOperators();
    }

}
